package org.ftc.web;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.ftc.domain.Users;
import org.ftc.form.UsersForm;
import org.ftc.service.FtcLogService;
import org.ftc.service.FtcLogService.Log;
import org.ftc.service.LoadUserDataTaskService;
import org.ftc.service.RoleAuthService;
import org.ftc.service.UsersService;
import org.ftc.service.UsersService.TypeCode;
import org.ftc.util.Global;
import org.ftc.util.ListCalculator;
import org.ftc.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.SAXException;

@Controller
public class UsersController {

	@Autowired
	private UsersService usersService;
	@Autowired
	private RoleAuthService roleAuthService;
	@Autowired
	private FtcLogService logService;
	@Autowired
	private LoadUserDataTaskService loadService;

	@RequestMapping(value = "/users.htm")
	public String users(ModelMap model) {
		model.addAttribute("searchForm", new UsersForm());//
		model.addAttribute("roleAuth", roleAuthService.findAll());
		return "users/list";
	}

	@RequestMapping(value = "/users/list.json", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> list(UsersForm form, BindingResult binding,
			ModelMap model) {
		logService.before();
		form.setType(TypeCode.USERS.toString());
		model.put("searchForm", form);
		Map<String, Object> json = new HashMap<String, Object>();
		ListCalculator listCal = new ListCalculator();
		int pageSize = form.getRows();
		listCal.setRecordsPerPage(pageSize);
		Integer totalRecs = (int) usersService.count(form);
		int totalPages = listCal.totalPages(totalRecs);
		int pageNo = form.getPage();
		pageNo = (pageNo >= totalPages) ? totalPages : pageNo;
		int firstRes = listCal.firstResult(pageNo);
		json.put("total", totalRecs.toString());
		List<Users> users = usersService.findPage(form, firstRes, pageSize);
		json.put("rows", users);
		logService.save(Log.QUERY, this.getClass().toString());
		return json;
	}

	@RequestMapping(value = "/users/newForm.htm")
	public String form(ModelMap model) {
		Users usersForm = new Users();
		usersForm.setStatus(0);
		model.addAttribute("usersForm", usersForm);
		model.addAttribute("roleAuth", roleAuthService.findAll());
		return "users/save";
	}

	@RequestMapping(value = "/users/save.htm", method = RequestMethod.POST)
	public String save(Users entity, ModelMap model) {
		logService.before();
		entity.setType(TypeCode.USERS.name());
		usersService.save(entity);
		model.addAttribute("id", entity.getUsersSeq());
		logService.save(Log.INSERT, entity.getUsersSeq(), this.getClass().toString(),
				ToStringBuilder.reflectionToString(entity));
		return "redirect:/users/get.htm";
	}

	@RequestMapping(value = "/users/get.htm")
	public String get(@RequestParam("id") String id, ModelMap model) {
		logService.before();
		model.addAttribute("usersForm", usersService.get(id));
		model.addAttribute("roleAuth", roleAuthService.findAll());
		logService.save(Log.QUERY, this.getClass().toString());
		return "users/update";
	}

	@RequestMapping(value = "/users/update.htm", method = RequestMethod.POST)
	public String update(Users entity, ModelMap model) {
		logService.before();
		Users users = usersService.get(entity.getUsersSeq());
		users.setRole(entity.getRole());
		users.setStatus(entity.getStatus());
		usersService.update(users);
		model.addAttribute("id", users.getUsersSeq());
		logService.save(Log.UPDATE, users.getUsersSeq(), this.getClass().toString());
		return "redirect:/users/get.htm";
	}

	@RequestMapping(value = "/users/delete.json")
	public @ResponseBody String delete(@RequestParam("id") String id, ModelMap model) {
		Boolean s = true;
		logService.before();
		s = usersService.delete(id);
		logService.save(Log.DELETE, id, this.getClass().toString());
		return s.toString();
	}


	// 檢核帳號
	@RequestMapping(value = "/users/checkUserName.json", method = RequestMethod.POST)
	public @ResponseBody boolean check(UsersForm entity) {
		logService.before();
		Users user = usersService.findByUserName(entity.getUserName());
		logService.save(Log.QUERY, this.getClass().toString());
		if (user == null)
			return true;
		return false;
	}

	// 單位
	@RequestMapping(value = "/users/tokenByName.json")
	public @ResponseBody List<HashMap<String, String>> tokenByUnit(@RequestParam("q") String param) {
		logService.before();
		UsersForm form = new UsersForm();
		form.setName(param);
		logService.save(Log.QUERY, this.getClass().toString());
		return usersService.findByName(form);

	}

	@RequestMapping(value = "/users/getUser.json", produces = "application/json;charset=UTF-8")
	public @ResponseBody String getUser(@RequestParam("id") String id) {
		List<HashMap<String, String>> datas = usersService.findUsers(id);
		return Util.listToJson(datas);
	}
	
	
	@RequestMapping(value = "/users/load.json", method = RequestMethod.GET)
	public @ResponseBody boolean loadData() {
		logService.before();
		try {
			return loadService.update();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		logService.save(Log.INSERT_UPDATE,"", this.getClass().toString());
		return false;
	}
	
	/**
	 * 記錄者
	 * @return
	 */
	@RequestMapping(value = "/users/findRecorder.json", method = RequestMethod.GET)
	public @ResponseBody
	List<Users> findRecorder() {
		return usersService.findRecorder();
		
	}
	
	/**
	 * name
	 * @return
	 */
	@RequestMapping(value = "/users/userName.json", method = RequestMethod.GET)
	public @ResponseBody
	String userName(@RequestParam("id") String id) {
		return usersService.transferName(id);
		
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(Global.APP.DATE_FORMAT);
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}

}
